<template>
    <div>
        <div class="container">
            <el-table :data="tableData" border class="table" max-height="666" ref="singleTable"
                      header-cell-class-name="table-header">
                <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
                <el-table-column prop="title" label="标题" align="center"></el-table-column>
                <el-table-column prop="comment" label="备注" align="center"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
                <el-table-column prop="custom" label="标签" align="center"
                                 :filters="[{ text: 'custom', value: true }, { text: 'online', value: false }]"
                                 :filter-method="filterTag">
                    <template #default="scope">
                        <el-tag :type="scope.row.custom==true ? 'success' : 'warning'">
                            {{ scope.row.custom == true ? 'custom' : 'online' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="试听" align="center">
                    <template #default="scope">
                        <el-button icon="el-icon-headset" type="text"
                                   v-if="scope.row.url != ''"
                                   @click="listen(scope.row.url)">支持
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" align="center">
                    <template #default="scope">
                        <el-button type="text" icon="el-icon-edit" @click="edit(scope.row)">添加到
                        </el-button>
                        <el-button type="text" icon="el-icon-delete" class="red"
                                   @click="remove(scope.row.id)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>


            <el-row style="margin-top: 1em">
                <!-- 新增按钮 -->
                <el-col :span="8">
                    <el-button @click="add" type="primary" size="small">新增</el-button>
                </el-col>
                <!-- 分页器 -->
                <el-col :span="1" :offset="15">
                    <el-pagination background layout="total" :total=tableData.length></el-pagination>
                </el-col>
            </el-row>
        </div>

        <!-- 编辑弹框 -->
        <el-dialog title="添加到定时通知列表" v-model="editVisible" width="25em">
            <el-form label-width="25%">
                <el-form-item label="标题">
                    <el-tag>{{ editForm.title }}</el-tag>
                </el-form-item>
                <el-form-item label="开始时间">
                    <template #default="scope">
                        <el-time-select
                            v-model="editForm.startTime"
                            :clearable="false"
                            start="08:00" step="00:01" end="23:00"
                        >
                        </el-time-select>
                    </template>
                </el-form-item>
                <el-form-item label="次数">
                    <template #default="scope">
                        <el-input-number v-model="editForm.cycleNumber" :min="1" :max="10"/>
                    </template>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false" size="small">取消</el-button>
                    <el-button type="primary" @click="editsave(editForm)" size="small">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 试听弹窗 -->
        <el-dialog title="在线语音试听" v-model="listenVisible" width="25em" :destroy-on-close="true">
            <div align="center">
                <audio v-if="listenUrl.endsWith('.wav')" controls="controls" :src="listenUrl"></audio>
                <iframe v-if="!listenUrl.endsWith('.wav')" :src="listenUrl" height="80px"></iframe>
            </div>

        </el-dialog>

        <!-- 新增弹窗 -->
        <el-dialog title="新增语音" v-model="addVisible" :destroy-on-close="true" width="35em" center>
            <el-form label-width="5em" style="width: 90%">
                <el-form-item label="标题">
                    <el-input maxlength="10" show-word-limit v-model.trim="addForm.title"/>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input maxlength="20" show-word-limit v-model.trim="addForm.comment"/>
                </el-form-item>
                <el-form-item label="标签">
                    <el-select v-model="value" placeholder="Select">
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="音频">
                    <Recorder @blob="getFile"></Recorder>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible = false" size="small">取消</el-button>
                    <el-button type="primary" size="small" @click="addSave(addForm)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {
    ref,
    reactive,
} from "vue";
import {
    ElMessage,
    ElMessageBox
} from "element-plus";
import {
    addBroadcast,
    addVoice,
    upload,
    getVoiceList,
    removeVoice
} from "../api/broadcast";
import Recorder from "../components/Recorder.vue";
import {getDateTime} from "../utils/time";

export default {
    name: "voiceList",
    components: {Recorder},
    setup() {
        //初始化窗口状态
        const editVisible = ref(false);
        const listenVisible = ref(false);
        const addVisible = ref(false);

        //初始化表格数据
        const tableData = ref([]);

        //初始化试听地址
        let listenUrl = ref('');

        //初始化编辑弹窗表单内容
        let editForm = reactive({
            voiceId: "",
            title: "",
            startTime: "12:00",
            cycleNumber: 1,
        });

        //新增弹窗下拉选择器
        const value = ref('custom')
        const options = [
            {
                value: 'custom',
                label: 'custom',
            },
            {
                value: 'online',
                label: 'online',
            },
        ]

        //初始化新增弹窗表单内容
        let addForm = reactive({
            title: "",
            comment: "",
            createTime: '',
            custom: '',
            url: '',
        });

        //获取录音器组件传来的url
        const getFile = (f) => {
            addForm.url = f;
            console.log(f.type);
        }

        //这里定义好，后面刷新时要调用
        const getData = () => {
            getVoiceList().then((res) => {
                tableData.value = res.data;
            });
        };

        //获取表格数据
        getData();

        //定义编辑操作
        const edit = (row) => {
            editForm['voiceId'] = row['id'];
            editForm['title'] = row['title'];
            editVisible.value = true;
        };

        //定义编辑保存操作
        const editsave = (form) => {
            editVisible.value = false;
            addBroadcast(form)
                .then((res) => {
                    if (res.data === true) {
                        ElMessage.success('添加成功！');
                        //重新加载实现刷新页面效果
                        getData();
                    } else {
                        ElMessage.error('添加失败，请稍后重试！');
                    }
                })
                .catch(() => {
                    ElMessage.error('服务器未启动或其它错误！');
                });
            //刷新页面（无效果）
            //this.reload();
        };

        //定义新增操作
        const add = () => {
            addVisible.value = true;
        }

        //定义新增保存操作
        const addSave = async (form) => {
            if (form.title === '') {
                ElMessage.error('标题不能为空！');
            } else {
                addVisible.value = false;
                form.createTime = getDateTime(new Date);
                // console.log('aaaaaaaaaa', form)
                //将文件上传至服务器
                await upload(form.url)
                    .then((res) => {
                        if (res.code === 0) {
                            form.url = res.data;
                        } else {
                            ElMessage.error('服务器上传失败，请稍后重试！');
                        }
                    })
                    .catch(() => {
                        ElMessage.error('服务器未启动或其它错误！');
                    })
                if (value.value == 'custom') {
                    form.custom = true;
                } else {
                    form.custom = false;
                }
                addVoice(form)
                    .then((res) => {
                        if (res.data === true) {
                            ElMessage.success('添加成功！');
                            //重新加载实现刷新页面效果
                            getData();
                            Object.keys(addForm).forEach((item) => {
                                addForm[item] = '';
                            })
                        } else {
                            ElMessage.error('添加失败，请稍后重试！');
                        }
                    })
                    .catch(() => {
                        ElMessage.error('服务器未启动或其它错误！');
                    });
            }


        }

        //定义删除操作
        const remove = (id) => {
            ElMessageBox.confirm(
                "确定要在语音库中删除吗？", "提示", {
                    type: "warning",
                })
                .then(() => {
                    //向服务器发送删除请求
                    removeVoice(id)
                        .then(res => {
                            if (res.data === true) {
                                ElMessage.success("删除成功");
                                //刷新表格数据
                                getData();
                            } else {
                                ElMessage.error("删除失败，请稍后再试！");
                            }
                        })
                        .catch(() => {
                            ElMessage.error('服务器未启动或其它错误！');
                        })
                    //刷新页面
                    //this.reload();
                })
                .catch(() => {
                });
        };

        //标签过滤操作
        const filterTag = (value, row) => {
            return row.custom === value;
        };

        //定义试听操作
        const listen = (url) => {
            listenVisible.value = true;
            listenUrl.value = url;
        }

        return {
            tableData,
            editVisible,
            editForm,
            addForm,
            listenVisible,
            addVisible,
            listenUrl,
            value,
            options,
            filterTag,
            remove,
            edit,
            editsave,
            addSave,
            listen,
            add,
            getFile
        };
    },
};
</script>

<style scoped>
.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}
</style>